package cn.zmwh.manage.admin.modules.upms.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.constants.Constants;
import cn.zmwh.common.security.annotation.PreRole;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysMenu;
import cn.zmwh.manage.admin.modules.upms.pojo.request.SysMenuRequest;
import cn.zmwh.manage.admin.modules.upms.pojo.vo.SysMenuNode;
import cn.zmwh.manage.admin.modules.upms.service.SysMenuService;
import cn.zmwh.manage.admin.modules.upms.service.SysRoleMenuService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-11
 */
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/api/menu")
public class SysMenuController {

    @Autowired
    public SysMenuService sysMenuService;
    @Autowired
    public SysRoleMenuService sysRoleMenuService;

    @ApiOperation("树形结构返回所有菜单列表")
    @GetMapping(value = "/nav")
    public Result<List<SysMenuNode>> treeList(@ApiIgnore @RequestHeader(Constants.UID) Long uid, @ApiIgnore @RequestHeader(Constants.USERNAME) String userName) {

        List<SysMenuNode> list = sysMenuService.treeList(uid, userName);
        return Result.ok(list);
    }


    @PostMapping
    @ApiOperation(value = "保存")
    @PreRole(role = "ADMIN", name = "编辑菜单")
    public Result<String> save(@RequestBody SysMenuRequest req) {

        SysMenu sysMenu = new SysMenu();
        BeanUtil.copyProperties(req, sysMenu);
        if (req.getId() != null) {
            sysMenu.setCreateTime(new Date());
        }
        sysMenu.setMetaStr(JSONUtil.toJsonStr(req.getMeta()));
        sysMenu.setUpdateTime(new Date());
        sysMenuService.saveOrUpdate(sysMenu);
        return Result.success();
    }


    @PostMapping("/del/{id}")
    @ApiOperation(value = "删除")
    @PreRole(role = "ADMIN", name = "删除菜单")
    public Result<String> delete(@PathVariable("id") Long id) {
        // 判断是否有子菜单或按钮
        List<SysMenu> list = sysMenuService.list(Wrappers.<SysMenu>lambdaQuery()
                .eq(SysMenu::getPid, id));
        if (CollUtil.isNotEmpty(list)) {
            return Result.failed("请先删除子菜单");
        }
        sysMenuService.removeById(id);
        sysRoleMenuService.delByMenu(id);
        return Result.success();
    }

}

